{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "from tensorflow.contrib.tensorboard.plugins import projector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n",
      "Iter 0, Testing Accuracy= 0.4075\n",
      "Iter 100, Testing Accuracy= 0.8064\n",
      "Iter 200, Testing Accuracy= 0.8243\n",
      "Iter 300, Testing Accuracy= 0.8298\n",
      "Iter 400, Testing Accuracy= 0.8688\n",
      "Iter 500, Testing Accuracy= 0.8836\n",
      "Iter 600, Testing Accuracy= 0.8985\n",
      "Iter 700, Testing Accuracy= 0.9005\n",
      "Iter 800, Testing Accuracy= 0.902\n",
      "Iter 900, Testing Accuracy= 0.9053\n",
      "Iter 1000, Testing Accuracy= 0.907\n"
     ]
    }
   ],
   "source": [
    "#载入数据集\n",
    "mnist = input_data.read_data_sets(\"MNIST_data/\",one_hot=True)\n",
    "#运行次数\n",
    "max_steps = 1001\n",
    "#图片数量\n",
    "image_num = 3000\n",
    "#文件路径\n",
    "DIR = \"D:/Tensorflow/\"\n",
    "\n",
    "#定义会话\n",
    "sess = tf.Session()\n",
    "\n",
    "#载入图片\n",
    "embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding')\n",
    "\n",
    "#参数概要\n",
    "def variable_summaries(var):\n",
    "    with tf.name_scope('summaries'):\n",
    "        mean = tf.reduce_mean(var)\n",
    "        tf.summary.scalar('mean', mean)#平均值\n",
    "        with tf.name_scope('stddev'):\n",
    "            stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n",
    "        tf.summary.scalar('stddev', stddev)#标准差\n",
    "        tf.summary.scalar('max', tf.reduce_max(var))#最大值\n",
    "        tf.summary.scalar('min', tf.reduce_min(var))#最小值\n",
    "        tf.summary.histogram('histogram', var)#直方图\n",
    "\n",
    "#命名空间\n",
    "with tf.name_scope('input'):\n",
    "    #这里的none表示第一个维度可以是任意的长度\n",
    "    x = tf.placeholder(tf.float32,[None,784],name='x-input')\n",
    "    #正确的标签\n",
    "    y = tf.placeholder(tf.float32,[None,10],name='y-input')\n",
    "\n",
    "#显示图片\n",
    "with tf.name_scope('input_reshape'):\n",
    "    image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])\n",
    "    tf.summary.image('input', image_shaped_input, 10)\n",
    "\n",
    "with tf.name_scope('layer'):\n",
    "    #创建一个简单神经网络\n",
    "    with tf.name_scope('weights'):\n",
    "        W = tf.Variable(tf.zeros([784,10]),name='W')\n",
    "        variable_summaries(W)\n",
    "    with tf.name_scope('biases'):\n",
    "        b = tf.Variable(tf.zeros([10]),name='b')\n",
    "        variable_summaries(b)\n",
    "    with tf.name_scope('wx_plus_b'):\n",
    "        wx_plus_b = tf.matmul(x,W) + b\n",
    "    with tf.name_scope('softmax'):    \n",
    "        prediction = tf.nn.softmax(wx_plus_b)\n",
    "\n",
    "with tf.name_scope('loss'):\n",
    "    #交叉熵代价函数\n",
    "    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\n",
    "    tf.summary.scalar('loss',loss)\n",
    "with tf.name_scope('train'):\n",
    "    #使用梯度下降法\n",
    "    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)\n",
    "\n",
    "#初始化变量\n",
    "sess.run(tf.global_variables_initializer())\n",
    "\n",
    "with tf.name_scope('accuracy'):\n",
    "    with tf.name_scope('correct_prediction'):\n",
    "        #结果存放在一个布尔型列表中\n",
    "        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置\n",
    "    with tf.name_scope('accuracy'):\n",
    "        #求准确率\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#把correct_prediction变为float32类型\n",
    "        tf.summary.scalar('accuracy',accuracy)\n",
    "\n",
    "#产生metadata文件\n",
    "if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'):\n",
    "    tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv')\n",
    "with open(DIR + 'projector/projector/metadata.tsv', 'w') as f:\n",
    "    labels = sess.run(tf.argmax(mnist.test.labels[:],1))\n",
    "    for i in range(image_num):   \n",
    "        f.write(str(labels[i]) + '\\n')        \n",
    "        \n",
    "#合并所有的summary\n",
    "merged = tf.summary.merge_all()   \n",
    "\n",
    "\n",
    "projector_writer = tf.summary.FileWriter(DIR + 'projector/projector',sess.graph)\n",
    "saver = tf.train.Saver()\n",
    "config = projector.ProjectorConfig()\n",
    "embed = config.embeddings.add()\n",
    "embed.tensor_name = embedding.name\n",
    "embed.metadata_path = DIR + 'projector/projector/metadata.tsv'\n",
    "embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png'\n",
    "embed.sprite.single_image_dim.extend([28,28])\n",
    "projector.visualize_embeddings(projector_writer,config)\n",
    "\n",
    "for i in range(max_steps):\n",
    "    #每个批次100个样本\n",
    "    batch_xs,batch_ys = mnist.train.next_batch(100)\n",
    "    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n",
    "    run_metadata = tf.RunMetadata()\n",
    "    summary,_ = sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata)\n",
    "    projector_writer.add_run_metadata(run_metadata, 'step%03d' % i)\n",
    "    projector_writer.add_summary(summary, i)\n",
    "    \n",
    "    if i%100 == 0:\n",
    "        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\n",
    "        print (\"Iter \" + str(i) + \", Testing Accuracy= \" + str(acc))\n",
    "\n",
    "saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps)\n",
    "projector_writer.close()\n",
    "sess.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
